package com.wantupai.translate.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.linchaolong.android.imagepicker.cropper.CropImageOptions;
import com.linchaolong.android.imagepicker.cropper.CropImageView;
import com.wantupai.translate.Constant;
import com.wantupai.translate.R;
import com.wantupai.translate.base.BaseActivity;
import com.wantupai.translate.bean.DataBean;
import com.wantupai.translate.bean.TranslateBean;
import com.wantupai.translate.bean.WordBean;
import com.wantupai.translate.utils.MyLog;
import com.wantupai.translate.utils.NetUtils;
import com.wantupai.translate.utils.NetworkUtils;
import com.wantupai.translate.utils.ToastUtils;
import com.wantupai.translate.activity.TranslateActivity;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.wantupai.translate.Constant.ImagePath;

/**
 * @author luxuchang
 * @date 2019/4/23 0023
 * @description
 */
public class PicActivity extends BaseActivity implements CropImageView.OnSetImageUriCompleteListener, CropImageView.OnCropImageCompleteListener {
    @BindView(R.id.iv_surface_view)
    ImageView ivSurfaceView;
    @BindView(R.id.clip_iv)
    CropImageView clipView;
    @BindView(R.id.trans_first)
    TextView transFirst;
    @BindView(R.id.trans_second)
    TextView transSecond;

    private boolean isTranslate;
    private CropImageOptions mOptions;
    private String picPath;
    private String t1, t2;

    @Override
    protected boolean translucentStatusBar() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_pic;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initViews() {
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        setTitle("裁剪");
        initOptions();
    }

    @Override
    public void initListener() {
    }

    @Override
    public void initData() {
        picPath = getIntent().getStringExtra("picPath");
        if (getIntent() != null && getIntent().hasExtra("Translate"))
            isTranslate = getIntent().getBooleanExtra("Translate", false);
//        Bitmap bitmap= BitmapFactory.decodeFile(picPath);
//        clipView.setImageBitmap(bitmap);
        clipView.setImageUriAsync(Uri.fromFile(new File(picPath)));
        Log.e("path", "saveComplete: " + picPath);
        t1 = transFirst.getText().toString();
        t2 = transSecond.getText().toString();
//        Glide.with(this).load(Uri.fromFile(new File(picPath))).into(ivSurfaceView);

//        image = ((BitmapDrawable) ivSurfaceView.getDrawable()).getBitmap();
    }

    private void uploadPic(final String picPath, final boolean translate) {
        Map<String, File> files = new HashMap<>();
        Map<String, String> maps = new HashMap<>();
        if (picPath == null)
            return;
        File file = new File(picPath);
        maps.put("type", "general");
        files.put("image", file);

        NetUtils.getInstance().upLoadFile(Constant.SSP_API_IMAGETOWORD, maps, files, true, WordBean.class, 1, new NetUtils.NetUpLoadFileListener() {
            @Override
            public void onLoading(long current, boolean isDownloading, int requestCode) {

            }

            @Override
            public void onSuccess(DataBean result, int requestCode) {
                if (requestCode == 1) {
                    List<WordBean> data = (List<WordBean>) result.getData();
                    StringBuilder txt = new StringBuilder();
                    for (int i = 0; i < data.size(); i++) {
                        if (i == data.size() - 1) {
                            txt.append(data.get(i).getWords());
                        } else {
                            txt.append(data.get(i).getWords());
                            txt.append("\n");
                        }
                    }
                    MyLog.e("sss", txt.toString());
                    MyLog.e("sss1", txt.toString().replace("\n", ""));
                    if (translate) {
                        translate(picPath, txt.toString().replace("\n", ""));
                    } else {
                        startActivity(new Intent(PicActivity.this, ResultActivity.class).putExtra("data", txt.toString()).putExtra("picPath", picPath));
                    }
//                    translate(txt.toString());
                }
            }

            @Override
            public void onFailed(int requestCode, String info) {
                ToastUtils.show(info);
            }
        });

//        RequestApi.uploadPicTranslate(Constant.SSP_API_IMAGETOWORD, maps, new AbstractNetWorkCallback<String>() {
//            @Override
//            public void onSuccess(String str) {
//                MyLog.e("sss", "onSuccess=" + str);
//            }
//
//            @Override
//            public void onError(String errorMsg) {
//                MyLog.e("sss", "errorMsg=" + errorMsg);
//            }
//        });
    }

    @Override
    public void processClick(View v) {

    }

    @Override
    protected void onStart() {
        super.onStart();
        clipView.setOnSetImageUriCompleteListener(this);
        clipView.setOnCropImageCompleteListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        clipView.setOnSetImageUriCompleteListener(null);
        clipView.setOnCropImageCompleteListener(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clipView.setOnSetImageUriCompleteListener(null);
        clipView.setOnCropImageCompleteListener(null);
    }


    public Bitmap crop(Rect frame, Bitmap image) {
        float[] src = new float[]{frame.left, frame.top};
        Matrix matrix = new Matrix();
        int width = frame.width();
        int height = frame.height();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        Bitmap originalBitmap = image;
        matrix.postTranslate(-src[0], -src[1]);
        canvas.drawBitmap(originalBitmap, matrix, null);
        return bitmap;
    }

    //保存方法
    private void saveFile(Bitmap bm, String fileName, boolean translate) throws IOException {
//        String subForder = Environment.getExternalStorageDirectory().getAbsolutePath()+"/wantupai/image/";
        File foder = new File(ImagePath);
        if (!foder.exists()) foder.mkdirs();

        File myCaptureFile = new File(ImagePath, fileName);
        Log.e("lgq", "图片保持。。。。wwww。。。。" + myCaptureFile);
//        ends = myCaptureFile.getPath();
        if (!myCaptureFile.exists()) myCaptureFile.createNewFile();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        uploadPic(myCaptureFile.getAbsolutePath(), translate);
    }

    private void translate(final String picPath, final String tct) {
        Map<String, String> maps = new HashMap<>();
        maps.put("q", tct);
//        if ("英文".equals(t1)) {
//            maps.put("from", "en");
//            maps.put("to", "cn");
//        } else {
//            maps.put("from", "cn");
//            maps.put("to", "en");
//        }

        maps.put("from", "cn");
        maps.put("to", "en");

        int NetType = NetworkUtils.getNetWorkType(this);
        if (NetType == 0) {
            Toast.makeText(this, "没有网络连接", Toast.LENGTH_SHORT).show();
        } else {
            NetUtils.getInstance().post(Constant.SSP_API_TRANSLATE, maps, false, TranslateBean.class, 7, new NetUtils.NetResponseListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onSuccess(DataBean result, int requestCode) {
//                    stopAnim();
                    TranslateBean bean = (TranslateBean) result.getData();
                    MyLog.e("bean", bean.getTrans_result().getDst());

                    startActivity(new Intent(PicActivity.this, TranslateActivity.class).putExtra("data", bean.getTrans_result().getSrc()).putExtra("trans_result", bean.getTrans_result().getDst()));

                }

                @Override
                public void onFailed(int requestCode, String info) {
                    if (requestCode == 99) {
                        finish();
                    } else {
                        Toast.makeText(getBaseContext(), info, Toast.LENGTH_SHORT).show();
                    }
//                    stopAnim();
                }
            });
        }
    }

    @OnClick({R.id.trans_first, R.id.trans_second, R.id.ssp_trans_top, R.id.btn_back, R.id.btn_sure, R.id.btn_refresh})
    public void onViewClicked(View view) {
//        if (TextUtils.isEmpty(PrefUtils.getString(Constant.TPUID,""))){
//            startActivity(new Intent(PicActivity.this,LoginActivity.class));
//            return;
//        }
        final Bitmap image;
        Rect frameRect;
        Bitmap crop;
        switch (view.getId()) {
            case R.id.trans_first:
            case R.id.trans_second:
            case R.id.ssp_trans_top:
                transFirst.setText(t2);
                transSecond.setText(t1);
                t1 = transFirst.getText().toString();
                t2 = transSecond.getText().toString();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_sure:
                cropImage();
                break;
            case R.id.btn_refresh:
                clipView.resetCropRect();
                break;
        }
    }

    private void error() {
        ToastUtils.show("图片出错");
        finish();
    }

    public void initOptions() {
        mOptions = new CropImageOptions();
        mOptions.activityTitle = "图片裁剪";
        mOptions.guidelines = CropImageView.Guidelines.ON;
        mOptions.cropShape = CropImageView.CropShape.RECTANGLE;
        mOptions.scaleType = CropImageView.ScaleType.CENTER_CROP;
        mOptions.outputRequestWidth = 540;
        mOptions.outputRequestHeight = 540;
        mOptions.aspectRatioX = 9;
        mOptions.aspectRatioY = 16;
        mOptions.fixAspectRatio = true;
    }

    private void cropImage() {
        if (mOptions.noOutputImage) {
            error();
        } else {
            Uri outputUri = getOutputUri();
            clipView.saveCroppedImageAsync(outputUri,
                    mOptions.outputCompressFormat,
                    mOptions.outputCompressQuality,
                    mOptions.outputRequestWidth,
                    mOptions.outputRequestHeight,
                    mOptions.outputRequestSizeOptions);
        }
    }

    private Uri getOutputUri() {
        Uri outputUri = mOptions.outputUri;
        if (outputUri.equals(Uri.EMPTY)) {
            try {
                String ext = mOptions.outputCompressFormat == Bitmap.CompressFormat.JPEG ? ".jpg" :
                        mOptions.outputCompressFormat == Bitmap.CompressFormat.PNG ? ".png" : ".webp";
                outputUri = Uri.fromFile(File.createTempFile("cropped", ext, getCacheDir()));
            } catch (IOException e) {
                throw new RuntimeException("Failed to create temp file for output image", e);
            }
        }
        return outputUri;
    }

    @Override
    public void onCropImageComplete(CropImageView view, CropImageView.CropResult result) {
        MyLog.e("uri=", result.getUri().toString());
        if (isTranslate){
            uploadPic(result.getUri().toString().replace("file://", ""), true);
        }else {
            uploadPic(result.getUri().toString().replace("file://", ""), false);
        }
    }

    @Override
    public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) {
        if (error == null) {
            if (mOptions.initialCropWindowRectangle != null) {
                clipView.setCropRect(mOptions.initialCropWindowRectangle);
            }
            if (mOptions.initialRotation > -1) {
                clipView.setRotatedDegrees(mOptions.initialRotation);
            }
        } else {
            error();
        }
    }

//    private void startLoadAnim() {
//        ssp_camera_anim_s.setVisibility(View.VISIBLE);
//        ssp_camera_anim.setVisibility(View.VISIBLE);
//        PropertyValuesHolder holder1 = PropertyValuesHolder.ofFloat("alpha", 1f, 0.3f, 1f);
//        PropertyValuesHolder holder2 = PropertyValuesHolder.ofFloat("scaleX", 1f, 0.8f, 1f);
//        PropertyValuesHolder holder3 = PropertyValuesHolder.ofFloat("scaleY", 1f, 0.8f, 1f);
//        PropertyValuesHolder holder4 = PropertyValuesHolder.ofFloat("rotation", 0f, 360f);
//
//        ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(ssp_camera_anim_s, holder1, holder2, holder3, holder4);
//        animator.setDuration(5000);
//        animator.setInterpolator(new LinearInterpolator());
//        animator.setRepeatCount(ValueAnimator.INFINITE);
//        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//            }
//        });
//        ObjectAnimator animator2 = ObjectAnimator.ofPropertyValuesHolder(ssp_camera_anim, holder1, holder2, holder3, holder4);
//        animator2.setDuration(4500);
//        animator2.setInterpolator(new LinearInterpolator());
//        animator2.setRepeatCount(ValueAnimator.INFINITE);
//        animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//            }
//        });
//        animator.start();
//        animator2.start();
//    }
//
//    public void stopAnim() {
//        ssp_camera_anim.clearAnimation();
//        ssp_camera_anim_s.clearAnimation();
////                ssp_camera_anim_ss.clearAnimation();
//        ssp_camera_anim.setVisibility(View.GONE);
//        ssp_camera_anim_s.setVisibility(View.GONE);
////                ssp_camera_anim_ss.setVisibility(View.GONE);
//    }
}
